package reflect.engine;

import java.util.List;

import object.model.JavaFile;
import object.model.JavaVariables;
import object.model.MySQL_TableDDL;

import com.mysql.opt.Operator;

public class DDLGenerator {
	static final String TableDropBody = "DROP TABLE IF EXISTS `[TB_NAME]`";
	static final String ViewDropBody = "DROP VIEW IF EXISTS `[TB_NAME]`";
	static final String DDLbody = "CREATE TABLE `[TB_NAME]` (" + Operator.nextline + 
								"[VAR_BODY]" + 
								"[KEY_BODY]" + 
								")";
	
	static final String VAR_BODY = "`[VAR_NAME]` [DATA_TYPE] [CONDICTION]";
	
	public static MySQL_TableDDL generateTableDDL(JavaFile jf){
		String name = jf.getClassName();
		String ddl = DDLbody.replace("[TB_NAME]", name);
		String drop = TableDropBody.replace("[TB_NAME]", name);
		String varBody = "";
		String keyBody = "PRIMARY KEY ([KEY_NAME])";
		String keyName = "";
		List<JavaVariables> jvL = jf.getVars();
		for(int i=0;i<jvL.size();i++){
			JavaVariables jv = jvL.get(i);
			String varName = jv.getVarName();
			varBody += VAR_BODY.replace("[VAR_NAME]", varName).
					replace("[DATA_TYPE]", jv.getMysqlDataType().toUpperCase()).
					replace("[CONDICTION]", jv.getCondiction()) + ((keyBody.equalsIgnoreCase("") && i==jvL.size()-1)?"":",") + Operator.nextline;
			if(jv.isPrimaryKey()){
				keyName += "`" + varName + "`,";
			}
		}
		ddl = ddl.replace("[VAR_BODY]", varBody);
		if(!keyBody.equalsIgnoreCase("")){
			keyBody = keyBody.replace("[KEY_NAME]", keyName.substring(0, keyName.length()-1)) + Operator.nextline;
		}else{
			keyBody = "";
		}
		ddl = ddl.replace("[KEY_BODY]", keyBody);
		MySQL_TableDDL mDDL = new MySQL_TableDDL(jf.getClassName(), jf.getType());
		mDDL.setCreateTable(ddl);		
		return mDDL;
	}
		
}
